<?php

namespace User\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\Authentication\AuthenticationService;
use User\Model\Entity\UserInterface as User;

class UserName extends AbstractHelper {
	/**
	 * @var AuthenticationService
	 */
	protected $authService;

	/**
	 * @param UserInterface $user
	 * @throws User\Exception\DomainException
	 * @return String
	 */
	public function __invoke(User $user = null) {
		if (null === $user) {
			if ($this->getAuthService()->hasIdentity()) {
				$user = $this->getAuthService()->getIdentity();
				if (!$user instanceof User) {
					throw new \User\Exception\DomainException(
                        '$user is not an instance of User', 500
					);
				}
			} else {
				return false;
			}
		}

		$name = $user->getName();
		if (null === $name) {
			$name = $user->getEmail();
			$name = substr($name, 0, strpos($displayName, '@'));
		}

		return $name;
	}

	/**
	 * @return AuthenticationService
	 */
	public function getAuthService() {
		return $this->authService;
	}

	/**
	 * @param AuthenticationService $authService
	 * @return UserName
	 */
	public function setAuthService(AuthenticationService $authService) {
		$this->authService = $authService;
		return $this;
	}
}